package com.sportizz.sport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Typeface;

import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.UiLifecycleHelper;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;
//import com.sportizz.sport.R;
import com.sportizz.model.sports;

@SuppressLint("HandlerLeak")
public class StartActivity extends Activity {

	private Session.StatusCallback statusCallback = new SessionStatusCallback();

	public static String APP_ID = "578743002204440";

	public static Facebook facebook = new Facebook(APP_ID);
	// private AsyncFacebookRunner mAsyncRunner;
	String FILENAME = "AndroidSSO_data";
	public static SharedPreferences mPrefs;
	public static boolean is_app_start = false;

	private boolean istablet = false;

	String country_code;
	String imei;
	String email_id;
	public ProgressDialog pDialog;
	DbHandler handler;
	DatabaseAdapter dat_adapter;

	public static Activity first_act;

	String result = null;
//	public static final String rssFeed = "http://sportizza.com/interface/ios_filter.php";
	com.sportizz.sport.AlertDialogManager alert = new com.sportizz.sport.AlertDialogManager();

//	AsyncTask<String, Void, Void> MyTask;

	public TextView start_text, start_text1;
	public static HashMap<String, String> json;

	public static HashMap<String, String> player_name;
	public static HashMap<String, String> name_list;
	List<sports> sport_adp;
	sports sport;

	public String first = "true";

	public static Context Context_start;

	public static int Lmt_f, foll_count;

	public static SharedPreferences newShared;
	public static SharedPreferences follow_count;
	public static SharedPreferences temp_prefs, limited_follow;
	public static String get_img_location = null;

	public static SharedPreferences preferences, preferences_i_fo,
			preferences_db;

	public static SharedPreferences pref_newsport_code, pref_newsport_name;
	public static ProgressBar pb1;

	public static RelativeLayout start_layout;
	String start_a = null;

//	Button Fb_Login, btn_skip;

	public static UiLifecycleHelper uiHelper;

	public static List<String> f_txt_date, s_txt_date, t_txt_date,
			f0_txt_match, f1_txt_match, s0_txt_match, s1_txt_match,
			t0_txt_match, t1_txt_match;
	public static List<String> champ_game_txt, channel_list;

	public static String what_new="";

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Hides the titlebar
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		final Window win = getWindow();
		win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
				| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
				| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		setContentView(R.layout.start);
   
		// mAsyncRunner = new AsyncFacebookRunner(facebook);

		start_layout = (RelativeLayout) findViewById(R.id.start_layout);

		uiHelper = new UiLifecycleHelper(this, statusCallback);

		Context_start = this;
		first_act = this;

		// champ_game_txt = new ArrayList<String>();
		//
		// f_txt_date=new ArrayList<String>();
		s_txt_date = new ArrayList<String>();
		t_txt_date = new ArrayList<String>();
		// f0_txt_match=new ArrayList<String>();
		f1_txt_match = new ArrayList<String>();
		s0_txt_match = new ArrayList<String>();
		s1_txt_match = new ArrayList<String>();
		t0_txt_match = new ArrayList<String>();
		t1_txt_match = new ArrayList<String>();

		dat_adapter = new DatabaseAdapter(this);

		dat_adapter.open();

		dat_adapter.create_follow_tab();
		
//		dat_adapter.test_old();
		
//		dat_adapter.insert_follow_info_old("13339", "Argentina", "SOC", "FOOTBALL", "ARG", "Y");
//		dat_adapter.insert_follow_info_old("2113", "Garcia-lopez", "TEN", "TENNIS", "ESP", "N");
		
//		Fb_Login = (Button) findViewById(R.id.FB_Login);
//		btn_skip = (Button) findViewById(R.id.btn_skip);

		start_text = (TextView) findViewById(R.id.start_text);
		start_text1 = (TextView) findViewById(R.id.start_text1);

		follow_count = Context_start.getSharedPreferences("Follow_count",
				Context.MODE_PRIVATE); 
   
		preferences = PreferenceManager
				.getDefaultSharedPreferences(StartActivity.this);

		preferences_i_fo = PreferenceManager
				.getDefaultSharedPreferences(StartActivity.this);

		preferences_db = PreferenceManager
				.getDefaultSharedPreferences(StartActivity.this);

		foll_count = follow_count.getInt("follow_count", 0);

		pb1 = (ProgressBar) findViewById(R.id.progressBar_first);// .setVisibility(true);

		Context context3 = StartActivity.this;

		Context context = StartActivity.this;
		newShared = context.getSharedPreferences("startActivity",
				Context.MODE_PRIVATE);

		limited_follow = context3.getSharedPreferences("limited_follow",
				Context.MODE_PRIVATE);

		Lmt_f = limited_follow.getInt("max_follow", 3);

		Log.e("suraj", "LIMITED FOLLOW = " + Lmt_f);
		Log.e("suraj",
				"count FOLLOW = " + follow_count.getInt("follow_count", 0));

		Log.e("suraj", "TIME  = " + TimeZone.getDefault().getID());

		// if (TimeZone.getDefault().getID().contains("America") == true) {
		// get_img_location = "http://sportizza.com";
		// } else {
		// get_img_location = "http://covenitis.com";
		// }

		if (Utils.isNetworkAvailable(StartActivity.this) == true) {
			findViewById(R.id.start_loding).setVisibility(View.GONE);

			Typeface sport_font = Typeface.createFromAsset(getAssets(),
					"hel57.ttf");

			start_text.setTypeface(sport_font);
			start_text1.setTypeface(sport_font);

			findViewById(R.id.start_text).setVisibility(View.VISIBLE);
			findViewById(R.id.start_text1).setVisibility(View.VISIBLE);
			findViewById(R.id.start_logo).setVisibility(View.VISIBLE);

			Thread t = new Thread(new Runnable() {

				@Override
				public void run() {

					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							startMain();
							// updateView();
						}
					});
				}
			});
			t.start();

		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					StartActivity.this);
			builder.setMessage("Please check internet connection..")
					.setTitle("Connection Problem")
					.setCancelable(false)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {

									StartActivity.first_act.finish();

								}

							});

			AlertDialog alert = builder.create();
			alert.show();
			// alert.showAlertDialog(StartActivity.this, "Connection Problem",
			// "Please check internet connection..", false);

		}
		long startTime1 = System.currentTimeMillis();

		Log.w("suraj", "Start Time= " + startTime1);

		istablet = isTablet(this);

		handler = new DbHandler(getBaseContext());
		Log.d("suraj", "Network = " + Utils.isNetworkAvailable(this));

		mPrefs = getPreferences(MODE_PRIVATE);

		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

		Session session = Session.getActiveSession();
		if (session == null) {
			if (savedInstanceState != null) {
				session = Session.restoreSession(this, null, statusCallback,
						savedInstanceState);
			}
			if (session == null) {
				session = new Session(this);
			}
			Session.setActiveSession(session);
			if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
				session.openForRead(new Session.OpenRequest(this)
						.setCallback(statusCallback));
			}
		}

		// if (Utils.isNetworkAvailable(StartActivity.this) == true) {
		// updateView();
		// } else {
		// alert.showAlertDialog(StartActivity.this, "Connection Problem",
		// "Please check internet connection..", false);
		// finish();
		// }

		// btn_skip.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {

		// startMain();
		// finish();
		// }
		// });

		// Fb_Login.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// if (Utils.isNetworkAvailable(StartActivity.this) == true) {
		// // loginToFacebook();
		// onClickLogin();
		// } else {
		// alert.showAlertDialog(StartActivity.this,
		// "Connection Problem",
		// "Please check internet connection..", false);
		// finish();
		// }
		// }
		//
		// });
   
	}

	@SuppressWarnings("deprecation")
	protected void loginToFacebook() {

		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);

		if (access_token != null) {
			facebook.setAccessToken(access_token);

			startMain();

			Log.d("FB Sessions", "" + facebook.isSessionValid());
		}

		if (expires != 0) {
			facebook.setAccessExpires(expires);
		}

		if (!facebook.isSessionValid()) {
			facebook.authorize(this,
					new String[] { "email", "publish_stream" },
					new DialogListener() {

						@Override
						public void onCancel() {
						}

						@Override
						public void onComplete(Bundle values) {
							SharedPreferences.Editor editor = mPrefs.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();

							startMain();
						}

						@Override
						public void onError(DialogError error) {

						}

						@Override
						public void onFacebookError(FacebookError fberror) {

						}

					});
		}
	}

	private void onClickLogin() {
	}
  
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// facebook.authorizeCallback(requestCode, resultCode, data);
		Log.v("suraj", "12============" + requestCode + "=== " + resultCode);
		if (requestCode == 10) {
			if (resultCode == 300) {
				startMain();
			} else if (resultCode == 200) {
				finish();
			}
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		return;
	}

	public String GetDeviceID(Context context) {

		String deviceId = Secure.getString(context.getContentResolver(),
				Secure.ANDROID_ID);
		Log.d("suraj", "Device ID= " + deviceId);
		return deviceId;

	}

	public static String GetCountryCode(Context context) {

		String country_code = "us";
		TelephonyManager manager1 = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);

		country_code = manager1.getSimCountryIso();

		if (country_code == null) {
			return "us";
		} else {
			return country_code;
		}
	}

	public void showToast(String msg) {
		Toast.makeText(StartActivity.this, msg, Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (pDialog != null && pDialog.isShowing()) {
			pDialog.cancel();
		}
	}

	public static boolean isTablet(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}

	public void startMain() {

		AsyncTask<Void, Void, ArrayList<String>> wait = new AsyncTask<Void, Void, ArrayList<String>>() {

			@Override
			protected void onPostExecute(ArrayList<String> result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);

				pb1.setVisibility(View.GONE);
				findViewById(R.id.start_loding).setVisibility(View.GONE);

				String first_time_str;

				if (Utils.isNetworkAvailable(StartActivity.this) == true) {

					country_code = GetCountryCode(StartActivity.this);

					first_time_str = preferences.getString("first_time", null);

					String first_time_str_db = preferences_db.getString(
							"first_time_db", null);

					Log.v("suraj_", "first_time_str_db - " + first_time_str_db);

					
					if (first_time_str_db == null) {
						
						
						try {

							for(int i=0;i<result.size();i++)
							{
								String data = result.get(i);
								String[] pl_data = data.split(":");
								
								String follow_ty = "";
								
								if(pl_data[5].equals("A"))
								{
									follow_ty ="C";
								}
								else if(pl_data[5].equals("Y") || pl_data[5].equals("N"))
								{
									follow_ty ="P";
								}
								
								dat_adapter.insert_follow_info(pl_data[0], pl_data[1], pl_data[2], pl_data[3], pl_data[4], pl_data[5], follow_ty);
								
							}
							
							dat_adapter.insert_default_value_setting();

							String lang_string = Utils
									.readJsonFeed(
											"http://sportizza.com/interface/ios_get_news_lang.php",
											StartActivity.this);

							JSONArray array_lang = new JSONArray(lang_string);

							int array_len = array_lang.length();

							for (int i = 0; i < array_len; i++) {

								JSONObject JsonObject_lang = array_lang
										.getJSONObject(i);

								dat_adapter.insert_lang(JsonObject_lang
										.getString("ss_language_id"),
										JsonObject_lang
												.getString("ss_news_language"));

							}
							SharedPreferences.Editor edit_db = preferences_db
									.edit();
							edit_db.putString("first_time_db", "OK");
							edit_db.commit();

						} catch (Exception e) {
							e.printStackTrace();
						}

					}

					if (first_time_str == null) {

						
						email_id = com.sportizz.model.UserEmailFetcher
								.getEmail(StartActivity.this);

						Log.v("suraj", "Email - " + email_id);

						imei = GetDeviceID(StartActivity.this);

						if (email_id != null) {

							dat_adapter.close();

							country_code = GetCountryCode(StartActivity.this);

							Intent intent = new Intent(StartActivity.this,
									sport_follow_class.class);
							// startActivity(intent);//(intent, 10);

							// Intent intent = new Intent(StartActivity.this,
							// MainActivity.class);
							intent.putExtra("country_code", country_code);
							intent.putExtra("email", email_id);
							intent.putExtra("device_id", imei);
							intent.putExtra("istablet", istablet);
							// Bundle b=new Bundle();
							// b.putSerializable("map",
							// player_name);
							// intent.putExtras(b);
							// intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
							startActivity(intent);

						} else {
							alert.showAlertDialog(StartActivity.this,
						 			"No accounts found",
									"You need  setup to a (Google) account.",
									false);

						}
					} else {
						email_id = com.sportizz.model.UserEmailFetcher
								.getEmail(StartActivity.this);

						Log.v("suraj", "Email - " + email_id);

						imei = GetDeviceID(StartActivity.this);

						if (email_id != null) {

							dat_adapter.close();

							Intent intent = new Intent(StartActivity.this,
									MainActivity.class);
							// startActivity(intent);//(intent, 10);

							// Intent intent = new Intent(StartActivity.this,
							// MainActivity.class);
							intent.putExtra("country_code", country_code);
							intent.putExtra("email", email_id);
							intent.putExtra("device_id", imei);
							intent.putExtra("istablet", istablet);
							// Bundle b=new Bundle();
							// b.putSerializable("map",
							// player_name);
							// intent.putExtras(b);
							// intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
							startActivity(intent);
						} else {
							alert.showAlertDialog(StartActivity.this,
									"No accounts found",
									"You need  setup to a (Google) account.",
									false);

						}
					}

				} else {

					alert.showAlertDialog(StartActivity.this,
							"Connection Problem",
							"Please check internet connection..", false);
					finish();
				}
			}

			@Override
			protected void onPreExecute() {
				// start_layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.mainback));
				pb1.setVisibility(View.VISIBLE);
				findViewById(R.id.start_loding).setVisibility(View.VISIBLE);

				findViewById(R.id.start_text).setVisibility(View.GONE);
				findViewById(R.id.start_text1).setVisibility(View.GONE);
				findViewById(R.id.start_logo).setVisibility(View.GONE);


				super.onPreExecute();
			}

			@Override
			protected ArrayList<String> doInBackground(Void... params) {
				
				Log.i("new_version","dat_adapter.istablePresent() = "+dat_adapter.istablePresent());
				
				ArrayList<String> old_data =new ArrayList<String>();
				
				country_code = GetCountryCode(StartActivity.this);
				
				try {
				String new_t = Utils.readJsonFeed(
						"http://sportizza.com/interface/get_image_new.php?iso_cd="+country_code,
						StartActivity.this);

				
					String[] new_tab = new_t.split(",");

					get_img_location = new_tab[0];

					// } else {
					// get_img_location = "http://covenitis.com";
					// }
					Log.d("suraj", " get_img_location =" + get_img_location);

					what_new = new_tab[1] + ":" + new_tab[2]+ ":" + new_tab[3]+ ":" + new_tab[4]+ ":" + new_tab[5];
				} catch (Exception e) {

					what_new = "";
					get_img_location = "http://sportizza.com/ss/images/";
				}
				
				String first_time_str_db = preferences_db.getString(
						"first_time_db", null);

				Log.v("suraj_", "first_time_str_db - " + first_time_str_db);

				if (first_time_str_db == null) {

					SharedPreferences.Editor edit_first = preferences
							.edit();
					edit_first.putString("first_time", null);
					edit_first.commit();
				}
				
				if(first_time_str_db ==null)
				{
					
					if(dat_adapter.istablePresent())
					{
						Cursor get_all_follow = dat_adapter.getAllfollow();
						
						get_all_follow.moveToFirst();
						
						do {
							 Log.d("new_version",""+get_all_follow.getString(get_all_follow
									.getColumnIndex("player_id")));

							 old_data.add(get_all_follow.getString(get_all_follow
									.getColumnIndex("player_id"))+":"+get_all_follow.getString(get_all_follow
											.getColumnIndex("player_name"))+":"+get_all_follow.getString(get_all_follow
													.getColumnIndex("sport_code"))+":"+get_all_follow.getString(get_all_follow
															.getColumnIndex("sport"))+":"+get_all_follow.getString(get_all_follow
																	.getColumnIndex("national"))+":"+get_all_follow.getString(get_all_follow
																			.getColumnIndex("is_team")));
							 
						} while (get_all_follow.moveToNext());
						
							dat_adapter.alter_table();
							dat_adapter.close();
							dat_adapter.open();
						
					}
					else
					{
						dat_adapter.create_new_follow();
					}
				}
				
				return old_data;
			}

		};
		wait.execute();

	}

	private void updateView() {

		// String access_token1 = mPrefs.getString("access_token", null);

		if (Session.getActiveSession().isOpened()) {

			startMain();

			Log.d("suraj", "@START" + Session.getActiveSession());
		} else {
			// Fb_Login.setText("Login");
			findViewById(R.id.start_logo).setVisibility(View.VISIBLE);
			findViewById(R.id.start_text).setVisibility(View.VISIBLE);
			findViewById(R.id.start_text1).setVisibility(View.VISIBLE);
//			Fb_Login.setVisibility(View.GONE);
//			btn_skip.setVisibility(View.GONE);

			new Thread(new Runnable() {

				@Override
				public void run() {

					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							findViewById(R.id.start_text).setVisibility(
									View.GONE);
							findViewById(R.id.start_text1).setVisibility(
									View.GONE);
							findViewById(R.id.start_loding).setVisibility(
									View.GONE);

							pb1.setVisibility(View.GONE);

//							Fb_Login.setVisibility(View.VISIBLE);
//							btn_skip.setVisibility(View.VISIBLE);
						}
					});
				}
			}).start();

		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		Session session = Session.getActiveSession();
		Session.saveSession(session, outState);
	}

	private class SessionStatusCallback implements Session.StatusCallback {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
		}
	}

}
